from django.shortcuts import render

# Create your views here.

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.http import Http404
from jobs.models import Job, Resume
from jobs.models import Cities,JobTypes
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from django.views.generic.detail import DetailView
# 3.加入视图，首先我用的函数做演示
def joblist(request):
    # 获取我们的列表信息，然后进行排序
    job_list=Job.objects.order_by('job_type')
    # 加载我们的模板
    # template=loader.get_template('joblist.html')
    # 定义一个上下文，是map类型
    context={'job_list':job_list}
    # 进行遍历我们的列表
    for job in job_list:
        job.city_name=Cities[job.job_city][1]
        job.job_type=JobTypes[job.job_type][1]
    # 返回我们遍历后的字符串数据
    # return HttpResponse(template.render(context))
    return render(request,'joblist.html',context)
# 3.1函数试图，我们这里加载详情页
def detail(request,job_id):
    try:
        job=Job.objects.get(pk=job_id)
        job.city_name=Cities[job.job_city][1]
    except job.DoesNotExist:
        raise Http404("job does not exist")
    return render(request,'job.html',{'job':job})

class ResumeDetailView(DetailView):
    '''
    简历详情页
    '''
    model = Resume
    template_name = 'resume_detail.html'




class ResumeCreateView(LoginRequiredMixin,CreateView ):
    template_name = 'resume_form.html'
    success_url = '/joblist'
    model=Resume
    fields = ['username','city','phone','email','apply_position','gender','training_school','bachelor_school',
             'master_school','doctor_school','major','degree','candidate_introduction','work_experience',
             'project_experience']
    # 从url请求参数带默认值
    def get_initial(self):
        initial={}
        for x in self.request.GET:
            initial[x]=self.request.GET[x]
        return initial
    # 跟当前用户做关联
    def form_valid(self, form):
        self.object=form.save(commit=False)
        self.object.applicant=self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())


